const connection = require('../config/database');

const purchaseOrderController = {
  // 获取所有进货单
  getAllOrders: async (req, res) => {
    const query = `
      SELECT po.*, d.name as dealer_name 
      FROM purchase_orders po
      LEFT JOIN dealers d ON po.dealer_id = d.id
      ORDER BY po.order_date DESC
    `;
    
    connection.query(query, (err, results) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      res.json(results);
    });
  },

  // 获取进货单详情
  getOrderById: async (req, res) => {
    const orderId = req.params.id;
    
    // 获取进货单基本信息
    const orderQuery = `
      SELECT po.*, d.name as dealer_name 
      FROM purchase_orders po
      LEFT JOIN dealers d ON po.dealer_id = d.id
      WHERE po.id = ?
    `;
    
    // 获取进货单明细
    const itemsQuery = `
      SELECT poi.*, 
        CASE 
          WHEN poi.item_type = 'book' THEN b.title
          ELSE g.name
        END as item_name
      FROM purchase_order_items poi
      LEFT JOIN books b ON poi.item_type = 'book' AND poi.item_id = b.isbn
      LEFT JOIN goods g ON poi.item_type = 'goods' AND poi.item_id = g.code
      WHERE poi.purchase_order_id = ?
    `;

    connection.query(orderQuery, [orderId], (err, orders) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }

      if (orders.length === 0) {
        res.status(404).json({ error: '进货单不存在' });
        return;
      }

      connection.query(itemsQuery, [orderId], (err, items) => {
        if (err) {
          res.status(500).json({ error: err.message });
          return;
        }

        res.json({
          ...orders[0],
          items: items
        });
      });
    });
  },

  // 创建进货单
  createOrder: async (req, res) => {
    const { dealer_id, items, notes } = req.body;
    
    // 计算总金额
    const total_amount = items.reduce((sum, item) => 
      sum + (item.quantity * item.unit_price * item.discount), 0);

    // 生成订单号 (年月日 + 4位随机数)
    const order_number = new Date().toISOString().slice(0,10).replace(/-/g,'') 
      + Math.floor(Math.random() * 10000).toString().padStart(4, '0');

    const order = {
      order_number,
      dealer_id,
      total_amount,
      notes
    };

    connection.beginTransaction(err => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }

      // 插入进货单
      connection.query('INSERT INTO purchase_orders SET ?', order, (err, result) => {
        if (err) {
          connection.rollback(() => {
            res.status(500).json({ error: err.message });
          });
          return;
        }

        const purchase_order_id = result.insertId;

        // 插入进货单明细
        const itemValues = items.map(item => [
          purchase_order_id,
          item.type,
          item.id,
          item.quantity,
          item.unit_price,
          item.discount,
          item.quantity * item.unit_price * item.discount
        ]);

        const itemsQuery = `
          INSERT INTO purchase_order_items 
          (purchase_order_id, item_type, item_id, quantity, unit_price, discount, total_price)
          VALUES ?
        `;

        connection.query(itemsQuery, [itemValues], (err) => {
          if (err) {
            connection.rollback(() => {
              res.status(500).json({ error: err.message });
            });
            return;
          }

          connection.commit(err => {
            if (err) {
              connection.rollback(() => {
                res.status(500).json({ error: err.message });
              });
              return;
            }
            res.json({ message: '进货单创建成功', order_id: purchase_order_id });
          });
        });
      });
    });
  },

  // 更新进货单状态
  updateOrderStatus: async (req, res) => {
    const { id } = req.params;
    const { status, payment_status, payment_amount } = req.body;

    const updates = {};
    if (status) updates.status = status;
    if (payment_status) updates.payment_status = payment_status;
    if (payment_amount) updates.payment_amount = payment_amount;

    connection.query(
      'UPDATE purchase_orders SET ? WHERE id = ?',
      [updates, id],
      (err, result) => {
        if (err) {
          res.status(500).json({ error: err.message });
          return;
        }
        res.json({ message: '进货单更新成功' });
      }
    );
  }
};

module.exports = purchaseOrderController; 